<script setup lang="ts">
import {onMounted, ref, nextTick} from 'vue'
import TnReadMore from '@tuniao/tnui-vue3-uniapp/components/read-more/src/read-more.vue'
import {onLoad, onShow} from "@dcloudio/uni-app";
import {cancelOrderSubApi, projectDetailApi} from "@/api/home";
import TnIcon from "@tuniao/tnui-vue3-uniapp/components/icon/src/icon.vue";
import TnScrollListNew from '@/composables/LeftScroll/index.vue'
import TnModal from '@tuniao/tnui-vue3-uniapp/components/modal/src/modal.vue'
import { sunOrderStatus } from "@/utils/constants";
import ZeroMarkdownView from "@/zero-markdown-view/components/zero-markdown-view/zero-markdown-view.vue";
import {removeMarkdownSymbols} from "@/utils/common";
const stepsData = [
  {
    title: '未接单',
    icon: 'success-circle',
    activeIcon: 'success-circle',
    value: 0
  },
  {
    title: '已接单',
    icon: 'success-circle',
    activeIcon: 'success-circle',
    value: 1
  },
  {
    title: '已付定金（24小时可退）',
    icon: 'success-circle',
    activeIcon: 'success-circle',
    value: 2
  },
  {
    title: '项目开始',
    icon: 'success-circle',
    activeIcon: 'success-circle',
    value: 3
  },
  {
    title: '项目完成',
    icon: 'success-circle',
    activeIcon: 'success-circle',
    value: 4
  },
  {
    title: '尾款已支付',
    icon: 'success-circle',
    activeIcon: 'success-circle',
    value: 5
  },
  {
    title: '售后中',
    icon: 'success-circle',
    activeIcon: 'success-circle',
    value: 6
  },
  {
    title: '交易结束',
    icon: 'success-circle',
    activeIcon: 'success-circle',
    value: 7
  },
]
const scrollLeft = ref(0);
const beforeExpand = () => {
  console.log(11111111)
  toPage();
}
const detailData = ref<any>({});
const getDetailData = async (id: string) => {
  const res = await projectDetailApi(id);
  detailData.value = res?.data || {};
  setTimeout(() => {
    scrollLeft.value = 100;
  }, 2000)
}
const currentStep = ref(0);
let id = ""
onLoad((options): void => {
  id = options?.id || "";
})
onShow(() => {
  if(id) {
    getDetailData(id);
  }
  // doms.scrollLeft(100)
  // doms[0].scrollIntoView({ behavior: "smooth" });


})

const scrollListRef = ref();
onMounted(() => {
  // nextTick(() => {
  //   // 获取内部 scroll-view
  //   console.log(scrollListRef.value..querySelector(".item-container"))
  //   const query = uni.createSelectorQuery().in(scrollListRef.value);
  //   query
  //       .select(".tn-scroll-list__scroll-view") // 图鸟UI内部的 scroll-view class
  //       .node((res) => {
  //         const scrollView = res.node;
  //         scrollView.scrollLeft = 200; // 设置初始滚动位置，单位 px
  //       })
  //       .exec();
  // });
})

const sendPage = () => {
  uni.navigateTo({
    url: `/pages/message/detail/deyail?userId=${detailData.value.customerOpenid}&headSculpture=${detailData.value.headSculpture}&projectId=${detailData.value.id}&orderPayStatus=${detailData.value.orderPayStatus}`,
  })
}

const addFun = () => {
  uni.navigateTo({
    url: `/pages/order/subTrade/index?projectId=${detailData.value.id}`,
  })
}

const toPage = () => {
  uni.setStorageSync("descText", detailData.value.requirementDescription)
  uni.navigateTo({
    url: `/pages/order/desc/desc`,
  })
}

const statusClass = (status: string): any => {
  return {
    0: 'tag-gray',
    1: 'tag-lightblue',
    2: 'tag-blue',
    4: 'tag-lightblue'
  }[status]
}

const copyLink = (file: any) => {
  uni.setClipboardData({
    data: file.url,
    showToast: false,
    success: () => {
      uni.showToast({
        title: '复制成功',
        duration: 1000
      });
    },
    fail: (err) => {
      console.log('err', err);
    }
  })
}

const downloadFile = (file: any) => {
  const token = uni.getStorageSync('token')
  const userInfo = uni.getStorageSync('userInfo')
  if (!token || !userInfo?.nickname) {
    uni.showModal({
      title: '提示',
      content: '请先登录再访问该页面',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/pages/login/index' })
        }
      }
    })
    return false
  }
  uni.downloadFile({
    url: file.url, // 文件的下载链接
    success(res) {
      if (res.statusCode === 200) {
        uni.saveFile({
          tempFilePath: res.tempFilePath, // 下载后的临时文件路径
          success(res1) {
            uni.showToast({
              title: "文件下载成功",
              icon: 'none'
            })
            console.log('文件保存成功', res1.savedFilePath); // 保存后的文件路径
            openFile(res1.savedFilePath)
          },
          fail(err) {
            uni.showToast({
              title: "文件下载失败",
              icon: 'none'
            })
            console.log('文件保存失败', err);
          }
        });

      }
    }
  });
}

const openFile = (filePath: string) => {
  uni.showToast({
    title: "正在打开文件",
    icon: "none"
  })
  uni.openDocument({
    filePath,
    showMenu: true, // 允许用户操作，如转发、保存到微信等
    success: () => {
      console.log('文件打开成功')
    },
    fail: (err: any) => {
      console.log(err);
      uni.showToast({
        title: '文件打开失败',
        icon: 'none'
      })
    }
  })
}


/**
 * 取消子订单
 * @param id
 */
const modalRef = ref<any>();
const cancelOrderSub = async (itemData: any) => {
  modalRef.value?.showModal({
    title: '提示',
    content: '确认取消订单吗？',
    showCancel: true,
    confirmText: '确认',
    cancelText: '取消',
    cancel: async () => {
      console.log('点击了取消按钮')
      return true;
    },
    confirm: async () => {
      const res = await cancelOrderSubApi(itemData.id);
      if (res.code === 200) {
        uni.showToast({
          title: '取消成功',
          icon: 'success',
          duration: 2000
        })
        getDetailData(id);
      } else {
        uni.showToast({
          title: res?.msg || '取消失败',
          icon: 'none',
        })
      }
      return true;
    },
  })

}

/**
 * 修改子订单
 */
const updateSub = (item: any) => {
  uni.setStorageSync("subOrderData", item)
  uni.navigateTo({
    url: `/pages/order/subTrade/index?projectId=${detailData.value.id}&update=true`,
  })
}
const leftMap = {
  0: 0,
  1: 100,
  2: 100,
  3: 350,
  4: 480,
  5: 600,
  6: 750,
  7: 750,
}
</script>
<template>
  <view class="page">
<!--    <TnScrollListNew style="width: 100vw" :componentId="5" :indicator="false" :scroll-x="true" ref="scrollListRef"-->
<!--                     :scroll-left="leftMap[detailData.orderStatus]">-->
<!--      <view class="item-container">-->
<!--        <view-->
<!--            v-for="(item, index) in stepsData"-->
<!--            :key="index"-->
<!--            class="scroll-item tn-flex-center tn-flex-column"-->
<!--            :class="'scroll-item' + index"-->
<!--        >-->
<!--          <view style="display: flex; align-items: center; color: #D8D8D8" :class="{'active-step': detailData.orderStatus >= index}">-->
<!--            <TnIcon size="16px" name="success-circle-fill"></TnIcon>-->
<!--            <text class="title" size="16px">{{ item.title }}</text>-->
<!--            <view class="scroll-list" v-if="index < stepsData.length - 1"></view>-->
<!--          </view>-->
<!--        </view>-->
<!--      </view>-->
<!--    </TnScrollListNew>-->
    <!-- 信息卡片 -->
    <view class="cu-card margin-top-sm">
      <view class="title">
        <text>主要信息</text>
      </view>
      <view class="cu-list menu mt-4">
        <view class="cu-item">
          <view class="content1">项目名称</view>
          <view class="text-gray">{{detailData.title}}</view>
        </view>
        <view class="cu-item">
          <view class="content1">类目</view>
          <view class="text-gray">{{detailData.categorySelectionOne}}-{{detailData.categorySelectionTwo}}</view>
        </view>
        <view class="cu-item">
          <view class="content1">期望时间</view>
          <view class="text-gray">{{ detailData.expectedDeliveryTime }}</view>
        </view>
        <view class="cu-item">
          <view class="content1">AI评估</view>
          <view class="text-gray">{{ detailData.aiTotalPrice }}元</view>
        </view>
        <view class="cu-item">
          <view class="content1">用户定价</view>
          <view class="text-gray">{{ detailData.totalPrice }}元</view>
        </view>
        <view class="cu-item">
          <view class="content1">定金</view>
          <view class="text-gray">{{ detailData.advancePrice }}元</view>
        </view>
      </view>
    </view>

    <!-- 开发语言 -->
    <view class="cu-card margin-top-sm">
      <view class="cu-list menu">
        <view class="cu-item">
          <view class="content1 text-333">追加服务</view>
          <view class="text-gray"> {{ detailData?.additionalServices || '无' }}</view>
        </view>
      </view>
    </view>

    <!-- 需求描述 -->
    <view class="cu-card margin-top-sm">
      <view class="cu-list menu">
        <view class="desc-box" @click="toPage">
          <view class="content1 text-333">需求描述</view>
          <TnIcon name="right" />
        </view>
        <view class="desc-content" style="line-height: 20px" >
          <TnReadMore tip-color="#4B7BF5" :before-expand="beforeExpand">
            <rich-text :nodes="removeMarkdownSymbols(detailData.requirementDescription)"></rich-text>
          </TnReadMore>
        </view>
      </view>
    </view>

    <view class="cu-card margin-top-sm" v-if="detailData?.attachmentsList?.length > 0">
      <view class="cu-list menu">
        <view class="desc-box">
          <view class="content1 text-333">附件</view>
        </view>
        <view class="desc-content">
          <view class="desc-content-item" v-for="item in detailData.attachmentsList">
            <view class="flex desc-content-item-left">
              <image src="@/assets/img/pdf.svg" v-if="item?.url?.includes('.pdf')" style="width: 20px; height: 20px;"></image>
              <image src="@/assets/img/excel.svg" v-if="item?.url?.includes('.xlsx') || item?.url?.includes('.xls')" style="width: 20px; height: 20px;"></image>
              <image src="@/assets/img/word.svg" v-if="item?.url?.includes('.doc') || item?.url?.includes('.docx')" style="width: 20px; height: 20px;"></image>
              <view style="max-width: 200px; overflow: scroll; white-space: nowrap; text-overflow: ellipsis">
                <view class="title-name">{{item.oldFileName}}</view>
                <view class="size-text">{{item.fileSize / 1000}}KB</view>
              </view>
            </view>
<!--            <view style="display: flex; align-items: center">-->
<!--              <image src="@/assets/img/load.svg" style="width: 15px; height: 20px; margin-right: 3px" @click="downloadFile(item)"></image>-->
<!--              <tnIcon size="15px" style="margin-left: 3px" name="copy" @click="copyLink(item)"></tnIcon>-->
<!--            </view>-->
          </view>
          <view class="line-item"></view>
        </view>
      </view>
    </view>
<!--    <view class="add-tip" v-if="detailData?.toOrderSubList?.length > 0">新增需求</view>-->
<!--      <view class="timeline">-->

<!--        <view v-for="(item, index) in detailData.toOrderSubList" :key="index" class="timeline-item">-->
<!--          &lt;!&ndash; 时间线圆点 &ndash;&gt;-->
<!--          <view class="dot" />-->

<!--          &lt;!&ndash; 内容区 &ndash;&gt;-->
<!--          <view class="content-fun">-->
<!--            <view class="header">-->
<!--              <view style="display: flex;align-items: center;margin-bottom: 10rpx;">-->
<!--                <text class="time">{{ item.createTime }}</text>-->
<!--                <view class="status-tag" :class="statusClass(item.orderPayStatus)">{{ sunOrderStatus[item.orderPayStatus] }}</view>-->
<!--              </view>-->

<!--              <view style="display: flex;align-items: center;">-->
<!--                <view class="btn-cancel" v-if="item.orderPayStatus === 1 || item.orderPayStatus === 2" @click="cancelOrderSub(item)">取消</view>-->
<!--                <view class="btn-cancel1" style="margin-left: 10px" v-if="item.orderPayStatus === 1" @click="updateSub(item)">修改</view>-->
<!--              </view>-->
<!--            </view>-->

<!--            <view class="card">-->
<!--              <view class="card-header">-->
<!--                <text class="title">需求:{{ item.title }}</text>-->
<!--                <text class="price">￥{{ item.totalPrice }}元</text>-->
<!--              </view>-->
<!--              <view class="desc">-->
<!--                {{item.requirementDescription}}-->
<!--              </view>-->
<!--            </view>-->
<!--          </view>-->
<!--          <view class="dot-end" v-show="index === detailData.toOrderSubList.length - 1" />-->
<!--        </view>-->

<!--      </view>-->

<!--    &lt;!&ndash; 底部按钮 &ndash;&gt;-->
<!--    <view class="bottom-box fixed-bottom padding">-->
<!--      <button class="handle-btn" @tap="sendPage" v-if="detailData.whetherEnable !== 0">发送消息</button>-->
<!--      <button class="handle-btn-lain"  v-if="detailData.orderStatus > 2" @tap="addFun">新加功能</button>-->
<!--    </view>-->

    <TnModal ref="modalRef" />

  </view>
</template>


<style scoped lang="scss">
.page {
  padding: 32rpx;
  background: #FAFAFA;
  .cu-card {
    border-radius: 16rpx;
    background-color: #fff;
    .title {
      margin-left: 44rpx;
      margin-top: 40rpx;
      color: #333333;
      font-size: 32rpx;
    }
    .content1 {
      margin-left: 16rpx;
      color: #999999;
      font-size: 32rpx;
      width: 190rpx;
    }
    .cu-item {
      justify-content: left !important;
    }
  }
  .text-333 {
    color: #333333 !important;

  }
  .cu-item::after {
    width: 186%;
    left: 3.5%;
    height: 200%;
  }
  .desc-box {
    position: relative;
    display: flex;
    padding: 0 30rpx;
    min-height: 100rpx;
    background-color: var(--white);
    justify-content: space-between;
    align-items: center;
    color: #666666;
  }
  .desc-content {
    color: #666666;
    padding: 0 46rpx 20rpx 46rpx;
    line-height: 56rpx;
    .desc-content-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .desc-content-item-left {
        display: flex;
        align-items: center;
      }
      .title-name {
        font-size: 28rpx;
        color: #000000;
        margin-left: 16rpx;
        font-weight: 500;
      }
      .size-text {
        font-size: 24rpx;
        color: #6B7280;
        margin-top: -10px;
        margin-left: 16rpx;
      }
    }
    .line-item {
      width: calc(100vw - 92rpx);
      margin-top: 10rpx;
      height: 1px;
      background-color: #F2F2F2;
      margin-left: -30rpx;
    }
  }
  :deep(.tn-step__mode-title) {
    font-size: 24rpx;
  }
  :deep(.tn-step__mode-item) {
    width: 30rpx;
    height: 30rpx;
  }
  :deep(.tn-step__mode-icon) {
    font-size: 32rpx;
  }
  :deep(.tn-steps__line) {
    width: 86rpx !important;
  }
  .handle-btn {
    background: #4B7BF5;
    border-radius: 160rpx;
    margin-bottom: 42rpx;
    font-size: 30rpx;
    color: #ffffff;
  }
  .handle-btn-lain {
    border:1px solid #4B7BF5;
    border-radius: 160rpx;
    margin-bottom: 42rpx;
    font-size: 30rpx;
    color: #4B7BF5;
  }
}
.add-tip {
  color: #333333;
  font-weight: 500;
  font-size: 32rpx;
  margin-top: 32rpx;
  margin-bottom: 16rpx;
  margin-left: 15px;
}
.timeline {
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 10px;
    bottom: 0;
    left: 3px;
    //transform: translateX(-50%);
    border-left: 5rpx dashed #81A5FF;
  }

  .timeline-item {
    position: relative;
    padding-bottom: 40rpx;
    display: flex;
    flex-direction: row;
    .dot {
      width: 16rpx;
      height: 16rpx;
      border-radius: 50%;
      background-color: #81A5FF;
      position: absolute;
      left: 0;
      top: 6rpx;
      z-index: 1;
    }
    .dot-end {
      width: 16rpx;
      height: 16rpx;
      border-radius: 50%;
      background-color: #81A5FF;
      position: absolute;
      left: 0;
      bottom: 0;
      z-index: 1;
    }

    .content-fun {
      margin-left: 30rpx;
      flex: 1;

      .header {
        display: flex;
        align-items: center;
        margin-bottom: 10rpx;
        justify-content: space-between;

        .time {
          font-size: 24rpx;
          color: #666666;
          margin-right: 12rpx;
        }

        .status-tag {
          font-size: 20rpx;
          padding: 4rpx 10rpx;
          border-radius: 8rpx;

          &.tag-gray {
            background: #F5F5F5;
            color: #999999;
            border-radius: 10px;
          }

          &.tag-blue {
            background: #4B7BF5;
            color: #FFFFFF;
            border-radius: 10px;
          }

          &.tag-lightblue {
            border: 1px solid #4B7BF5;
            color: #4B7BF5;
            border-radius: 10px;
          }
        }
      }

      .card {
        padding: 32rpx;
        border-radius: 18rpx;
        background: #ffffff;
        margin-top: 8px;
        .card-header {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10rpx;

          .title {
            font-weight: bold;
            font-size: 28rpx;
          }

          .price {
            color: #4B7BF5;
            font-weight: bold;
            font-size: 26rpx;
          }
        }

        .desc {
          font-size: 24rpx;
          color: #666666;
          line-height: 22px;
        }
      }
    }
  }
}
.item-container {
  position: relative;
  width: fit-content;

  display: flex;
  flex-wrap: nowrap;

  .scroll-item {
    flex-grow: 1;
    flex-shrink: 0;
    margin: 0rpx 10rpx;

    .empty {
      width: 100rpx;
      height: 100rpx;
      border-radius: 15rpx;
    }

    .title {
      margin-left: 10rpx;
      margin-right: 10rpx;
    }
  }
}
.scroll-list {
  background: #D8D8D8;
  height: 3px;
  width: 40px;
  border-radius: 3px;
}
.active-step {
  color: #1867FF !important;
  .scroll-list {
    background: #1867FF;
    border-radius: 3px;
  }
}
.btn-cancel {
  padding: 3px 5px;
  background: #D8D8D8;
  color: #333333;
  border-radius: 4px;
  margin-top: -5px;
}
.btn-cancel1 {
  padding: 3px 5px;
  background: #333333;
  color: #ffffff;
  border-radius: 4px;
  margin-top: -5px;
}
</style>
<style>
.tn-read-more {
  padding-bottom: 30px;
}
</style>
